import getopt
import mimetypes
import os.path
import sys
import pickle
import re
import time
import csv

import gdata.sample_util
import gdata.sites.client
import gdata.sites.data

SITES_DOMAIN = 'sadasystems.com'
SITES_SITENAME = 'lcf-ca-gov-copy-2'
CLIENT_ID = '96800280171-t8vvj9rpg5j6s4ke75ab7ks3gdrr32h6.apps.googleusercontent.com'
CLIENT_SECRET = 'Fj4aJNab0qRYG1cTtiYrsWu_'

#FIND_STRING =    """<img class="igm" data-igsrc="http://56.gmodules.com/ig/ifr?mid=56&amp;synd=trogedit&amp;url=http%3A%2F%2Fhosting.gmodules.com%2Fig%2Fgadgets%2Ffile%2F113993237013046360025%2FMenuSlideshowNotHomepage.xml&amp;h=380&amp;w=1040" data-props="align:left;borderTitle:hello world example;height:380;igsrc:http#58//56.gmodules.com/ig/ifr?mid=56&amp;synd=trogedit&amp;url=http%3A%2F%2Fhosting.gmodules.com%2Fig%2Fgadgets%2Ffile%2F113993237013046360025%2FMenuSlideshowNotHomepage.xml&amp;h=380&amp;w=1040;mid:56;scrolling:no;showBorder:false;showBorderTitle:null;spec:http#58//hosting.gmodules.com/ig/gadgets/file/113993237013046360025/MenuSlideshowNotHomepage.xml;width:1040;" data-type="ggs-gadget" height="380" src="http://www.google.com/chart?chc=sites&amp;cht=d&amp;chdp=sites&amp;chl=%5B%5BGoogle+Gadget'%3D20'f%5Cv'a%5C%3D0'10'%3D1039'0'dim'%5Cbox1'b%5CF6F6F6'fC%5CF6F6F6'eC%5C0'sk'%5C%5B%22Not+Home%22'%5D'a%5CV%5C%3D12'f%5C%5DV%5Cta%5C%3D10'%3D0'%3D1040'%3D377'dim'%5C%3D10'%3D10'%3D1040'%3D377'vdim'%5Cbox1'b%5Cva%5CF6F6F6'fC%5CC8C8C8'eC%5C'a%5C%5Do%5CLauto'f%5C&amp;sig=4DZqDg2swlvqkQwCwXdZrQSvAv4" style="display:block;text-align:left;margin-right:auto;" width="1040" />"""
FIND_STRING = """<img class="igm" data-igsrc="http://112.gmodules.com/ig/ifr?mid=112&amp;synd=trogedit&amp;url=https%3A%2F%2Fdarin-test.googlecode.com%2Fgit%2Fhelloandroidgadget.xml&amp;h=200&amp;w=100%25" data-props="align:left;borderTitle:hello world example;height:200;igsrc:http#58//112.gmodules.com/ig/ifr?mid=112&amp;synd=trogedit&amp;url=https%3A%2F%2Fdarin-test.googlecode.com%2Fgit%2Fhelloandroidgadget.xml&amp;h=200&amp;w=100%25;mid:112;scrolling:no;showBorder:true;showBorderTitle:true;spec:https#58//darin-test.googlecode.com/git/helloandroidgadget.xml;width:100%;" data-type="ggs-gadget" height="200" src="http://www.google.com/chart?chc=sites&amp;cht=d&amp;chdp=sites&amp;chl=%5B%5BGoogle+Gadget'%3D20'f%5Cv'a%5C%3D0'10'%3D499'0'dim'%5Cbox1'b%5CF6F6F6'fC%5CF6F6F6'eC%5C0'sk'%5C%5B%22hello+world+example%22'%5D'a%5CV%5C%3D12'f%5C%5DV%5Cta%5C%3D10'%3D0'%3D500'%3D197'dim'%5C%3D10'%3D10'%3D500'%3D197'vdim'%5Cbox1'b%5Cva%5CF6F6F6'fC%5CC8C8C8'eC%5C'a%5C%5Do%5CLauto'f%5C&amp;sig=HoDGbBfKikiLQG6hE5cmw7OW2qY" style="display:block;text-align:left;margin-right:auto;" width="500" />"""
#REPLACE_STRING = """<img data-type="ggs-gadget" data-props="url:https#58//darin-test.googlecode.com/git/helloandroidgadget.xml;showBorder:true;showBorderTitle:true;borderTitle:hello world example;title:hello world example;scrolling:no;width:100%;height:200;screenshot:https#58//ssl.gstatic.com/sites/p/d7beb8/system/app/images/cleardot.gif;params:;align:left" style="display: block; text-align: left;" data-igsrc="http://112.gmodules.com/ig/ifr?mid=112&amp;synd=trogedit&amp;url=https%3A%2F%2Fdarin-test.googlecode.com%2Fgit%2Fhelloandroidgadget.xml&amp;h=200&amp;w=100%25" allowtransparency="true" scrolling="no" frameborder="0" class="igm" src="https://www.google.com/chart?chc=sites&amp;cht=d&amp;chdp=sites&amp;chl=%5B%5BGoogle+Gadget'%3D20'f%5Cv'a%5C%3D0'10'%3D399'0'dim'%5Cbox1'b%5CF6F6F6'fC%5CF6F6F6'eC%5C0'sk'%5C%5B%22hello+world+example%22'%5D'a%5CV%5C%3D12'f%5C%5DV%5Cta%5C%3D10'%3D0'%3D400'%3D197'dim'%5C%3D10'%3D10'%3D400'%3D197'vdim'%5Cbox1'b%5Cva%5CF6F6F6'fC%5CC8C8C8'eC%5C'a%5C%5Do%5CLauto'f%5C&amp;sig=-xKA3CImFJ-3Y8hjQhqmF36CsXg" height="200" width="400"/>"""
REPLACE_STRING =    """<img class="igm" data-igsrc="http://56.gmodules.com/ig/ifr?mid=56&amp;synd=trogedit&amp;url=http%3A%2F%2Fhosting.gmodules.com%2Fig%2Fgadgets%2Ffile%2F113993237013046360025%2FMenuSlideshowNotHomepage.xml&amp;h=380&amp;w=1040" data-props="align:left;borderTitle:hello world example;height:380;igsrc:http#58//56.gmodules.com/ig/ifr?mid=56&amp;synd=trogedit&amp;url=http%3A%2F%2Fhosting.gmodules.com%2Fig%2Fgadgets%2Ffile%2F113993237013046360025%2FMenuSlideshowNotHomepage.xml&amp;h=380&amp;w=1040;mid:56;scrolling:no;showBorder:false;showBorderTitle:null;spec:http#58//hosting.gmodules.com/ig/gadgets/file/113993237013046360025/MenuSlideshowNotHomepage.xml;width:1040;" data-type="ggs-gadget" height="380" src="http://www.google.com/chart?chc=sites&amp;cht=d&amp;chdp=sites&amp;chl=%5B%5BGoogle+Gadget'%3D20'f%5Cv'a%5C%3D0'10'%3D1039'0'dim'%5Cbox1'b%5CF6F6F6'fC%5CF6F6F6'eC%5C0'sk'%5C%5B%22Not+Home%22'%5D'a%5CV%5C%3D12'f%5C%5DV%5Cta%5C%3D10'%3D0'%3D1040'%3D377'dim'%5C%3D10'%3D10'%3D1040'%3D377'vdim'%5Cbox1'b%5Cva%5CF6F6F6'fC%5CC8C8C8'eC%5C'a%5C%5Do%5CLauto'f%5C&amp;sig=4DZqDg2swlvqkQwCwXdZrQSvAv4" style="display:block;text-align:left;margin-right:auto;" width="1040" />"""


def findAndReplaceInSitePage(client, pageEntry, findString, replaceString):
    #remove the namespace prefixes that the Python XML parsing libary adds to the HTML(XML).
    originalHTML = re.sub(' xmlns:html="http://www.w3.org/1999/xhtml"', '', re.sub('<html:', '<', re.sub('</html:','</', pageEntry.content.html.ToString())))
    #originalHTML = (pageEntry.content.html.ToString())
    print "__________________ORIGINAL_____________________"
    print originalHTML
    #newHTML = re.sub(findString, replaceString, originalHTML)
    newHTML = originalHTML.replace(findString,replaceString);
    print "==================NEW HTML=====================";
    print newHTML
    if originalHTML != newHTML:
        pageEntry.content.html = newHTML
        client.Update(pageEntry)
        print 'Node: ' + pageEntry.GetNodeId() +' (' + pageEntry.GetHtmlLink().href + ') ' + 'has been updated'
    else:
        print 'Node: ' + pageEntry.GetNodeId() +' (' + pageEntry.GetHtmlLink().href + ') ' + 'has no changes'

def main():

    tokenfile = open("tokenfile", "r+b")
    token = gdata.gauth.OAuth2Token(
        client_id = CLIENT_ID,
        client_secret = CLIENT_SECRET,
        scope='https://sites.google.com/feeds/',
        user_agent='')
    authurl = token.generate_authorize_url()
    print authurl
    try:
        token = pickle.load(tokenfile)
    except:
        code = raw_input('AuthURL: ' + authurl + '\nWhat is the verification code? ').strip()
        token.get_access_token(code)
        print token.refresh_token
        print pickle.dump(token, tokenfile)
    tokenfile.close()

    client = gdata.sites.client.SitesClient(site=SITES_SITENAME, domain=SITES_DOMAIN)
    token.authorize(client)
    uri = client.make_content_feed_uri()
    page_count = 0
   
    with open('aboutpage.csv','rb') as csvfile:
        feedreader = csv.reader(csvfile, delimiter=',')
        for row in feedreader:
            path = row[0]
            print '{}'.format(path)
            pages = client.GetContentFeed(uri=uri,path=path)
            if len(pages.entry) != 1:
                print 'More than one entry in path query!!!'
            else:
                page = pages.entry[0]
                findAndReplaceInSitePage(client,page,FIND_STRING,REPLACE_STRING)
            
            page_count += 1
            

    print '{}'.format(page_count)

if __name__ == '__main__':
  main()